package com.qzct.utils;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.qzct.entity.vo.ResultVo;
import io.jsonwebtoken.Claims;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class JwtInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (request.getMethod().equals("OPTIONS")) {
            return true;
        }
        String token = request.getHeader("token");
        if (token == null || JwtUtils.verifyJwt(token)==null) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.setContentType("application/json");
            response.setCharacterEncoding("UTF-8");
            ObjectMapper objectMapper = new ObjectMapper();
            String jsonResponse = objectMapper.writeValueAsString(ResultVo.err( "令牌失效！"));
            response.getWriter().write(jsonResponse);
            return false;
        }
//        token = token.replace("Bearer ", "");
//        try {
//            Claims claims = JwtUtils.verifyJwt(token);
//            System.out.println("claims = " + claims);
//            request.setAttribute("user", claims.getSubject());
//            return true;
//        } catch (Exception e) {
//            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
//            return false;
//        }
        return true;
    }
}
